package org.cll.lagou.study.minicat.server;

import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2020/7/6 19:10
 */
public class IClassLoader extends ClassLoader {

    private static final Logger logger = LoggerFactory.getLogger(IClassLoader.class);

    @SneakyThrows
    @Override
    protected Class<?> findClass(String name) {

        InputStream inputStream = getClassInputStreamFromPath(name);
        if (null == inputStream) {
            return super.findClass(name);
        }

        byte[] bytes = new byte[inputStream.available()];
        int readLength = inputStream.read(bytes);
        logger.info("====== read length from = {} is {}", name, readLength);
//                        return defineClass(name, bytes, 0, bytes.length);
        return defineClass(null, bytes, 0, bytes.length);
    }

    private InputStream getClassInputStreamFromPath(String fileName) throws FileNotFoundException {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            return new FileInputStream(fileName);
        } else {
            return null;
        }
    }
}
